<?php

		class Sessions extends CI_Controller {
		
				function __construct(){
						parent::__construct();
				}
				
				function index(){
						die('index');
				}
				
				function _resolve_lang(){
						$langs = array('en','fr');
						$lang  = '';
						for($i=3;$i<$this->uri->total_segments();$i++)
						{
								if($this->uri->segment($i)=='lang' && $this->uri->segment($i+1) && in_array($this->uri->segment($i+1),$langs))
								{
										$lang = $this->uri->segment($i+1);
										break;
								}
						}
						if(!$lang && $this->session->userdata('sess_lang'))
						{
								$lang = $this->session->userdata('sess_lang');
						}
						if( !in_array($lang,$langs) ) $lang = $langs[0];
						if($lang) $this->session->set_userdata('sess_lang', $lang);
						return $lang;
				}
				
				function _resolve_token(){
						$token  = '';
						for($i=3;$i<$this->uri->total_segments();$i++)
						{
								if($this->uri->segment($i)=='token' && $this->uri->segment($i+1))
								{
										$token = $this->uri->segment($i+1);
										break;
								}
						}
						return $token;
				}
				
				function login(){
						if( $this->_auth_required('normal','',TRUE) )
						{
								redirect(base_url().'account/home');
						}
						
						$lang = $this->_resolve_lang();
						$this->lang->load('sessions_login', $lang);
						
						$localized_errors		= array (
								'error_field_required' => $this->lang->line('error_field_required'),
						);
						$data['locale'] 						= array();
						$data['locale']['lang']					= $lang;
						$data['locale']['errors']				= $localized_errors;
						$data['locale']['msg_loading']			= $this->lang->line('msg_loading').'...';
						$data['locale']['msg_processing']		= $this->lang->line('label_processing');
						$data['token'] 							= $this->_resolve_token();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$info = parse_url(base_url());
						// print_r($info);
						$this->load->library('encrypt');
						$cookie = array(
								'name'   => '__lcc',
								'value'  => $this->encrypt->encode($this->input->ip_address()),
								'expire' => 2*60*60,
								'domain' => '.' . @$info['host'],
								'path'   => '/'
						);
						$this->input->set_cookie($cookie); 
						
						$this->load->library('template');
						$this->template->set_template('account');
						$this->template->write('title', $data['company_name'] . ' &middot; ' . $this->lang->line('page_title'));
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/account/header', array('base_url'=>base_url()));
						$this->template->write_view('content', 'sessions/login', $data);
						$this->template->write_view('head_content', 'sessions/script/header/login', $data);
						$this->template->write_view('footer', 'layouts/account/footer');
						$this->template->write_view('footer', 'sessions/script/footer/login', array('base_url'=>base_url()));
						$this->template->render();
				}
				
				function pass_reset(){
						
						$lang = $this->_resolve_lang();
						$this->lang->load('sessions_login', $lang);
						
						$localized_errors		= array (
								'error_field_required' => $this->lang->line('error_field_required'),
						);
						$data['locale'] 						= array();
						$data['locale']['lang']					= $lang;
						$data['locale']['errors']				= $localized_errors;
						$data['locale']['msg_loading']			= $this->lang->line('msg_loading').'...';
						$data['locale']['msg_processing']		= $this->lang->line('label_processing');
						$data['token'] 							= $this->_resolve_token();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						$this->load->view('sessions_pass_reset',$data);
				}
				
				function pass_reset_confirm(){
						
						$lang = $this->_resolve_lang();
						$this->lang->load('sessions_login', $lang);
						
						$localized_errors		= array (
								'error_field_required' => $this->lang->line('error_field_required'),
						);
						
						$uri = $this->uri->uri_to_assoc(3);
						
						if(!isset($uri['token']) OR !isset($uri['su']) OR !$uri['token'] OR !$uri['su'])
						{
								$this->session->set_flashdata('sessions_login','<p id="flash-sessions_login" style="color:#ff0000;font-weight:bold;">Invalid URL!</p>');
								redirect(base_url() . 'sessions/login/');
						}
						
						$pr = new Pass_reset_token();
						$pr->where('token',$this->security->xss_clean($uri['token']))
						   ->where('added >=',time()-2*24*60*60)
						   ->where('r_stat','active')
						   ->get(1);
						if( !$pr->exists() )
						{
								$this->session->set_flashdata('sessions_login','<p id="flash-sessions_login" style="color:#ff0000;font-weight:bold;">Invalid or expired URL!</p>');
								redirect(base_url() . 'sessions/login/');
						}
						
						$user = new User();
						$user->where('mt4_uid',$this->security->xss_clean($pr->uid))
							 ->get(1);
						if( !$user->exists() )
						{
								$this->session->set_flashdata('sessions_login','<p id="flash-sessions_login" style="color:#ff0000;font-weight:bold;">This account was not found!</p>');
								redirect(base_url() . 'sessions/login/');
						}
						
						$real_su = md5($pr->uid.''.$user->password.''.$pr->token);
						if( $real_su!=$uri['su'] )
						{
								$this->session->set_flashdata('sessions_login','<p id="flash-sessions_login" style="color:#ff0000;font-weight:bold;">Invalid URL!</p>');
								redirect(base_url() . 'sessions/login/');
						}
						
						$data['__guid'] 						= $pr->token;
						$data['locale'] 						= array();
						$data['locale']['lang']					= $lang;
						$data['locale']['errors']				= $localized_errors;
						$data['locale']['msg_loading']			= $this->lang->line('msg_loading').'...';
						$data['locale']['msg_processing']		= $this->lang->line('label_processing');
						$data['token'] 							= $this->_resolve_token();
						
						$opts = read_options('', 'OBJECT');
						
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						$this->load->view('sessions_pass_reset_confirm',$data);
				}
				
				function ajax_is_cookies_enabled(){
						if ( $this->input->is_ajax_request())  {
								if ( !$this->input->cookie($this->config->item('sess_cookie_name'))) {
										die(json_encode(array('stat'=>'disabled')));
								} else {
										die(json_encode(array('stat'=>'enabled')));
								}
						}
						die(json_encode(array('stat'=>'malformed')));
				}				
				
				function ajax_login(){
						log_message('error', "Session login [".$this->input->ip_address()."]:\n[".print_r($this->input->request_headers(),true).']');
						
						if( $this->input->is_ajax_request() && $this->input->post('user') && $this->input->post('pass') ) 
						{
								$lang = $this->_resolve_lang();
								$this->lang->load('sessions_login', $lang);
						
								$this->load->library('encrypt');
								
								if ( !$this->input->cookie('__lcc'))
								{
										die( json_encode(array('stat'=>'error','field_id'=>'login-status','msg'=>'Your browser does not accept cookies! Please, enable cookies, refresh this page and try logging in again.')) );
								}
								
								$user = new User();
								/*
								$user->where('password',$this->encrypt->encode($this->security->xss_clean($this->input->post('pass'))))
									 ->where('mt4_uid',$this->security->xss_clean($this->input->post('user')))
									 ->get(1);
								*/
								$user->where('mt4_uid',$this->security->xss_clean($this->input->post('user')))
									 ->get(1);
								
								$_mes 		= $this->encrypt->_mcrypt_exists;
								$_pass 		= $this->security->xss_clean($this->input->post('pass'));
								$dec_pass_1 = $this->encrypt->decode($user->password);
								$this->encrypt->_mcrypt_exists = !$_mes;
								$dec_pass_2 = $this->encrypt->decode($user->password);
								$this->encrypt->_mcrypt_exists = $_mes;
								
								//if( $user->exists() ) die("found p=$_pass d1=$dec_pass_1 d2=$dec_pass_2");
								
								if( $user->exists() && ($_pass==$dec_pass_1 OR $_pass==$dec_pass_2))
								{
										$user_id = $user->id;
										$mt4_uid = $user->mt4_uid;
										
										if( $user->u_stat=='locked' )
										{
												die( json_encode(array('stat'=>'error','field_id'=>'user','msg'=>'Your account is locked. Please contact admin!')) );
										}
										//die($this->security->xss_clean($this->input->post('pass')).' vs '.$this->encrypt->decode($user->password));
										$mirror_account = false;
										$ib				= false;
										if(preg_match('#^[a-zA-Z-]+-AUTO$#is', $user->mt4_group))
										{
												$mirror_account = true;
										}
										if(preg_match('#^[a-zA-Z-]+-IB$#is', $user->mt4_group))
										{
												$ib = true;
										}
										$sessdata = array(
											'uid'  		=> $user->id,
											'logged_in' => TRUE,
											'mirror'	=> $mirror_account,
											'ib'		=> $ib
										);
										$next_url = '';
										if( $this->input->post('__token') && $this->session->userdata($this->input->post('__token')) )
										{
												$next_url = $this->session->userdata($this->input->post('__token'));
												$this->session->set_userdata($this->input->post('__token'), '');
												$token = array($this->input->post('__token') => '');
												$this->session->unset_userdata($token);
										}
										$this->session->set_userdata($sessdata);
										
										log_activity('User #'.$mt4_uid.' successfully logged in from ' . $this->input->ip_address(), 'user', 'sessions', 'system');
										
										die( json_encode(array('stat'=>'success','msg'=>'','next_url'=>$next_url)) );
								}
								else
								{
										$user->clear();
										$user->where('mt4_uid',$this->security->xss_clean($this->input->post('user')))->get(1);
										if($user->exists())
										{
												log_activity('User #'.$user->mt4_uid.' failed logged in from ' . $this->input->ip_address(), 'user', 'sessions', 'system');
										}
										else
										{
												log_activity('Login failure from ' . $this->input->ip_address(), 'user', 'sessions', 'system');
										}
										die( json_encode(array('stat'=>'error','field_id'=>'user','msg'=>$this->lang->line('error_invalid_login'))) );
								}
						}
						else
						{
								die( json_encode(array('stat'=>'error','msg'=>'Incomplete request.')) );
						}
				}
				
				function ajax_reset_pass(){
						if( $this->input->is_ajax_request() && $this->input->post('user') ) 
						{
								$lang = $this->_resolve_lang();
								$this->lang->load('sessions_login', $lang);
						
								$user = new User();
								$user->where('mt4_uid',$this->security->xss_clean($this->input->post('user')))
									 ->get(1);
								if( $user->exists() )
								{
										$pr 		= new Pass_reset_token();
										$pr->uid 	= $this->security->xss_clean($this->input->post('user'));
										$pr->token 	= random_string('unique');
										$pr->added 	= time();
										$pr->r_stat = 'active';
										$pr->save();
										
										$tpl_email  = new Tpl_email(); $tpl_email->where('type','password_reset')->get(1);
										$subject	= $this->_map_client_presets($user->id, $tpl_email->subject);
										$message 	= $this->_map_client_presets($user->id, $tpl_email->message);
										
										$find		= array('{password_reset_url}');
										$replaceby  = array(base_url().'sessions/pass_reset_confirm/token/'.$pr->token.'/su/'.md5($pr->uid.''.$user->password.''.$pr->token).'/');
										$subject    = str_replace($find,$replaceby,$subject);
										$message    = str_replace($find,$replaceby,$message);
										
										$opts = read_options('', 'OBJECT');
										
										$this->load->library('email');
										$config['protocol'] 	= 'smtp';
										$config['smtp_host'] 	= ($opts->smtp_ssl=='yes' && substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
										$config['smtp_user'] 	= $opts->smtp_user;
										$config['smtp_pass'] 	= $opts->smtp_pass;
										$config['smtp_port'] 	= $opts->smtp_port;
										$config['mailtype'] 	= 'html';
										$config['charset'] 		= 'utf-8';
										$this->email->initialize($config);
										$this->email->set_newline("\r\n");
								
										$this->email->from($opts->smtp_user, $opts->company_name);
										$this->email->to($user->email);
										$this->email->subject($subject);
										$this->email->message($message);
										$this->email->send();
										
										log_activity('User #'.$user->mt4_uid.' sent password reset request from ' . $this->input->ip_address(), 'user', 'sessions', 'system');

										// echo $this->email->print_debugger();
										// die('okay');
										
										die( json_encode(array('stat'=>'success','msg'=>'A password reset link was sent to your e-mail','next_url'=>'')) );
								}
								else
								{
										die( json_encode(array('stat'=>'error','field_id'=>'user','msg'=>'This account login does not exists')) );
								}
						}
						else
						{
								die( json_encode(array('stat'=>'error','msg'=>'Incomplete request.')) );
						}
				}
				
				function _map_client_presets($user_id, $str) {
						$user = new User();
						$user->where('id',(int)$user_id)->get(1);
						$find = array(
								'{client_id}', 
								'{client_name}', 
								'{client_first_name}', 
								'{client_last_name}', 
								'{client_country}', 
								'{client_email}', 
								'{client_password}', 
								'{client_phonenumber}', 
								'{client_address1}', 
								'{client_address2}', 
								'{client_city}', 
								'{client_state}', 
								'{client_company}', 
								'{client_postcode}', 
								'{client_mt4_id}', 
								'{client_mirror_login}', 
								'{client_group}', 
								'{client_mt4_agent}', 
								'{client_leverage}', 
								'{client_stored_doc}', 
								'{client_signature_image}'
						);
						$replaceby = array(
								$user->id,
								$user->firstname . ($user->firstname&&$user->lastname?' ':'') . $user->lastname,
								$user->firstname,
								$user->lastname,
								$user->country,
								$user->email,
								$this->encrypt->decode($user->password),
								$user->phone,
								$user->address1,
								$user->address2,
								$user->city,
								$user->state,
								$user->business,
								$user->zip,
								$user->mt4_uid,
								$user->mirror_login_id,
								$user->mt4_group,
								$user->mt4_agent,
								$user->leverage,
								$user->stored_doc ? base_url().'data/'.$user->id.'/'.$user->stored_doc : '',
								$user->signature_image_200x122 ? '<img src="'.base_url().'data/'.$user->id.'/'.$user->signature_image_200x122.'" />' : ''
						);
						return str_replace($find,$replaceby,$str);
				}
				
				function ajax_save_new_pass(){
						if( $this->input->is_ajax_request() && $this->input->post('pass') && $this->input->post('pass2') && $this->input->post('__guid') ) 
						{
								$lang = $this->_resolve_lang();
								$this->lang->load('sessions_login', $lang);
								
								$pr = new Pass_reset_token();
								$pr->where('token',$this->security->xss_clean($this->input->post('__guid')))->get(1);
								if( !$pr->exists() )
								{
										die( json_encode(array('stat'=>'error','msg'=>'Invalid Request!')) );
								}
								
								$user = new User();
								$user->where('mt4_uid', $pr->uid)->get(1);
								if($user->exists() && !$this->_sync_mt4_pwd($user->mt4_uid, $this->input->post('pass')))
								{
										die( json_encode(array('stat'=>'success','msg'=>'An internal error occurred when changing password! Try it again.')) );
								}
								$user_id = $user->id;
								$mt4_uid = $user->mt4_uid;
								$user->clear();
								
								$this->load->library('encrypt');
								$user->where('mt4_uid', $pr->uid)->update(array('password'=>$this->encrypt->encode($this->input->post('pass'))));
								$user->clear();
								
								$user->where('mt4_uid',$pr->uid)->get(1);

								log_activity('User #'.$mt4_uid.' confirmed password change request from ' . $this->input->ip_address(), 'user', 'sessions', 'system');
								
								$pr->clear();
								$pr->where('token',$this->security->xss_clean($this->input->post('__guid')))
								   ->update(array('updted'=>time(),'r_stat'=>'inactive'));								   
									 
								die( json_encode(array('stat'=>'success', 'msg'=>'Your new password was successfully saved!')) );
						}
						else
						{
								die( json_encode(array('stat'=>'error', 'msg'=>'Incomplete request.')) );
						}
				}
				
				function _sync_mt4_pwd($login, $pass){
						$this->load->library('mt4');
						$opts = read_options('mt4_host,mt4_port', 'OBJECT');
						if($this->mt4->connect($opts->mt4_host, (int)$opts->mt4_port)===FALSE)
						{
								return false;
						}
						$params['login'] 	 = $login;
						$params['pass']  	 = $pass;
						$params['investor']  = 0;
						$answerData 		 = $this->mt4->request('changepassword', $params);
						if($answerData===FALSE) return false;
						if(isset($answerData['result']))
						{
								if($answerData['result']<0) return false;
								else return true;
						}
						return false;
				}
				
				function _auth_required($type='normal',$url='',$return = false){
						if( !$this->session->userdata('uid') ) {
								$token = random_string('unique');
								while($this->session->userdata($token))
								{
										$token = random_string('unique');
								}
								$url = $url ? $url : current_url();
								$this->session->set_userdata($token,$url);
								if($type=='ajax')
								{		
										if($return) return false;
										else die(json_encode(array('stat'=>'not_loggedin','next_url'=>base_url() . 'sessions/login/token/'.$token)));
								}
								else
								{
										if($return) return false;
										else redirect(base_url() . 'sessions/login/token/'.$token);
								}
						}
				 		$user = new User();
						$user->where('id',(int)$this->session->userdata('uid'))->get(1);
						if( !$user->exists() ) {
								$token = random_string('unique');
								while($this->session->userdata($token))
								{
										$token = random_string('unique');
								}
								$url = $url ? $url : current_url();
								$this->session->set_userdata($token,$url);
								if($type=='ajax')
								{
										if($return) return false;
										else die(json_encode(array('stat'=>'not_loggedin','next_url'=>base_url() . 'sessions/login/token/'.$token)));
								}
								else
								{
										if($return) return false;
										else redirect(base_url() . 'sessions/login/token/'.$token);
								}
						}
						return true;
				}
				
				function logout(){
						
						if ( $this->input->cookie($this->config->item('sess_cookie_name').'-P')) {
								$cookie = array(
										'name'   => $this->config->item('sess_cookie_name').'-P',
										'value'  => $this->input->cookie($this->config->item('sess_cookie_name')),
										'expire' => -1,
										'domain' => '.' . parse_url(base_url(), PHP_URL_HOST),
										'path'   => '/'
								);
								$this->input->set_cookie($cookie); 
						}
						
						if($this->session->userdata('uid'))
						{
								log_activity('user #' . $this->session->userdata('uid') . ' successfully logged out from ' . $this->input->ip_address(), 'users', 'sessions', 'system');
						}
						
						$sessdata = array(
								'uid'  		=> '',
								'logged_in' => FALSE
						);
						$this->session->unset_userdata($sessdata);
						$this->session->sess_destroy();
						redirect(base_url().'sessions/login');
				}
				
				
		}

/* End of file sessions.php */
/* Location: ./system/application/controller/sessions.php */		